package com.outfood.task;

import com.alibaba.fastjson.JSON;
import com.outfood.common.eleme.Result;
import com.outfood.common.order.Details;
import com.outfood.domain.Order;
import com.outfood.domain.Rule;
import com.outfood.domain.Store;
import com.outfood.service.IOrderService;
import com.outfood.service.IRuleService;
import com.outfood.service.IStoreService;
import com.outfood.service.impl.ElmeOperateServiceImpl;
import com.outfood.service.impl.MeiTuanOperateServiceImpl;
import com.rys.common.enums.SearchTypeEnum;
import com.rys.common.utils.DateUtils;
import com.rys.common.utils.Search;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author huisonglin
 * @Description
 * @PackageName outfood-platform
 * @Package com.outfood.task
 * @Date 2024-03-25 17:08
 * @Version 1.0
 */
@Component
@Log4j2
public class ScanElemeOrderTask {

    @Resource
    IStoreService storeService;
    @Resource
    ElmeOperateServiceImpl elmeOperateService;
    @Resource
    IOrderService orderService;
    @Resource
    IRuleService ruleService;



    @Scheduled(cron = "0 */1 * * * ?")
    public void scan(){
        long start  = new Date().getTime();
        log.info("--------------------------------------------开始获取饿了么待出餐订单------------------------------------------------------------");//
        List<Store> storeList = storeService.getList(new Search().add("storeStatus", SearchTypeEnum.EqualTo,"1").add("platform","ELEME").add("onlineStatus",SearchTypeEnum.EqualTo,"ONLINE"));
        storeList.forEach(store -> {
            try {
                if("FALSE".equals(store.getAutoOut())){
                    log.warn("{}没有开启自动出餐",store.getStoreName());
                    return;
                }
                ElmeOperateServiceImpl.Query query = new ElmeOperateServiceImpl.Query();
                query.setShopId(store.getRegionId());
                query.setKsid(store.getCookie());
                query.setStoreId(store.getId());
                List<Result> orderList = elmeOperateService.getOrderList(query);
                if(CollectionUtils.isEmpty(orderList)){
                    return ;
                }

                orderList.forEach(orderItem ->{
                    List<Store> ss = storeService.getList(new Search().add("regionId", SearchTypeEnum.EqualTo, orderItem.getShopId()));
                    if(CollectionUtils.isEmpty(ss)){
                        return;
                    }
                    if("FALSE".equals(ss.get(0).getAutoOut())){
                        log.warn("{}子门店没有开启自动出餐",store.getStoreName());
                        return;
                    }
                    Rule rule = ruleService.getList(new Search().add("storeId", SearchTypeEnum.EqualTo, ss.get(0).getId())).get(0);
                    Order order = new Order();
                    order.setOrderTime(orderItem.getActiveTime());
                    order.setTheoryOutTime(new Date(order.getOrderTime().getTime()+1000*60*rule.getTime()));
                    //order.setBuyerName(orderItem.get);
                    String foodName = orderItem.getFoodInfo().getGroups().get(0).getItems().stream().map(item -> item.getName()).collect(Collectors.joining(","));
                    order.setFoodName(foodName);

//                    order.setIncome(orderItem.getDetail().getChargeInfo().getFixedSettlementInfo().getSettleAmount()+"");
//                    order.setPoiId(orderItem.getCommonInfoObj().getWmPoiId()+"");
//                    order.setOrderNo(orderItem.getCommonInfoObj().getWm_poi_order_dayseq()+"");
//                    order.setBuyerName(orderItem.getDetail().getUserInfo().getRecipientName());
                    order.setOutStatus("READY");
                    order.setStoreId(store.getId());
                    order.setOrderNo(orderItem.getHeader().getDaySn());
                    order.setOrderSource("ELEME");
                    order.setOutTradeNo(orderItem.getId());
                    order.setPoiId(orderItem.getShopId()+"");
//                    order.setRider(orderItem.getDetail().getLogisticsInfo().getTitle());
//                    order.setOutTradeNo(orderItem.getCommonInfoObj().getWm_order_id_view()+"");
//                    order.setInfo(JSON.toJSONString(orderItem));
                    List<Order> result = orderService.getList(new Search().add("outTradeNo", SearchTypeEnum.EqualTo, orderItem.getId()));
                    if(CollectionUtils.isEmpty(result)){
                        orderService.add(order,"task");
                    }

                });
            } catch (Exception e) {
                log.error("获取订单失败",e);
            }

        });
        long end  = new Date().getTime();
        log.info("------------------------------------------获取待出餐订单结束共耗时{}ms------------------------------------------------------------",end-start);

    }

    @Scheduled(cron = "0/10 * * * * ? ")
    public void toOut(){
        long start  = new Date().getTime();
        log.info("------------------------------------------开始出餐------------------------------------------------------------");
        String time = DateUtils.getTime();
        List<Order> list = orderService.getList(new Search().add("orderSource","ELEME").add("outStatus", SearchTypeEnum.EqualTo, "READY").add("theoryOutTime",SearchTypeEnum.LessThanOrEqual,time));
        list.forEach(order -> {
            Store store =null;
            try {
                ElmeOperateServiceImpl.Query query = new ElmeOperateServiceImpl.Query();
                query.setOrderId(order.getId());
                store = storeService.get(order.getStoreId());
                if(!store.getOnlineStatus().equals("ONLINE")){
                    return;
                }
                //判断该poidId我们有没有绑定
                log.info("开始判断总店下面的分店是不是也在我们旗下  {} ",order.getPoiId());
                List<Store> subStores = storeService.getList(new Search().add("regionId",SearchTypeEnum.EqualTo,order.getPoiId()).add("storeStatus",SearchTypeEnum.EqualTo,"1"));
                if(CollectionUtils.isNotEmpty(subStores)){

                    Store subStore = subStores.get(0);
                    if(!subStore.getId().equals(store.getId())){
                        log.info("总店再我们旗下，设置该订单的归属");
                        subStore.setPStoreId(store.getId());
                        subStore.setOnlineStatus("ONLINE");
                        storeService.update(subStore.getId(),subStore,"task");
                        order.setStoreId(subStore.getId());
                        orderService.update(order.getId(),order,"task");
                    }else{
                        log.info("这个不是总店无需设置。。。。{}",order.getPoiId());
                    }

                }else{
                    log.info("总店不在我们旗下，直接跳过");
                    order.setOutStatus("EXCEPT");
                    orderService.update(order.getId(),order,"task");
                    return;
                }
                query.setKsid(store.getCookie());

                ElmeOperateServiceImpl.OutResult outResult = elmeOperateService.excuteOutFood(query);
                log.info(outResult);
                if(outResult.getError()!=null && outResult.getError().equals("000000")){
                    return;
                }
                if(outResult.getError() == null){
                    order.setOutStatus("OUTED");
                    order.setOutFoodTime(new Date());
                    orderService.update(order.getId(),order,"task");
                }else{
                    order.setOutStatus("EXCEPT");
                    orderService.update(order.getId(),order,"task");
                }
            } catch (Exception e) {
                if("401 Unauthorized".equals(e.getMessage())){
                    log.info("{}出餐时掉线了",store);
                    store.setOnlineStatus("OFF");
                    storeService.update(store.getId(),store,"task");
                }else{
                    order.setOutStatus("EXCEPT");
                    orderService.update(order.getId(),order,"task");
                    log.error("",e);
//                    log.info("开始将门店设置为离线");
                }
            }
        });
        long end  = new Date().getTime();
        log.info("------------------------------------------出餐结束共耗时{}ms------------------------------------------------------------",end-start);
    }


}
